package com.world.cat.service.sys;

import com.world.cat.dao.sys.MsgDao;
import com.world.cat.dao.sys.UserDao;
import com.world.cat.enums.ReadState;
import com.world.cat.model.sys.Msg;
import com.world.cat.model.sys.User;
import com.world.common.util.CollectionUtil;
import com.world.common.util.DateUtil;
import com.world.core.dao.GenericRepository;
import com.world.core.dao.Restrictions;
import com.world.core.dao.SimpleExpression;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class MsgService extends BaseService<Msg> {
    @Resource
    private MsgDao msgDao;
    @Resource
    private UserDao userDao;

    @Override
    public GenericRepository getDao() {
        return msgDao;
    }

    public void saveMsg(String handler, String objId, String title, String handleAction, String content, String username) {
        if (!handler.equals(username)) {
            Msg msg = new Msg(objId, title, handleAction, content, username);
            msgDao.save(msg);
        }
    }


    public List<Msg> getUnReadMsg(String username, Integer limit) {
        User user = userDao.findByUsername(username);
        Date date = user.getReadMsgTime();
        if (date == null) {
            date = user.getCreateTime();
        }
        String hql = "from Msg t where t.username='" + username + "' and t.createTime > '" + DateUtil.format("yyyy-MM-dd HH:mm:ss", date) + "' order by t.createTime desc";
        List<Msg> msgs = msgDao.findByHql(hql, limit);
        return msgs;
    }

    public long getUnReadMsgCount(String username) {
        User user = userDao.findByUsername(username);
        Date date = user.getReadMsgTime();
        if (date == null) {
            date = user.getCreateTime();
        }
        String hql = "select count(*) from Msg t where t.username='" + username + "' and t.createTime > '" + DateUtil.format("yyyy-MM-dd HH:mm:ss", date) + "' order by t.createTime desc";
        javax.persistence.Query query = msgDao.createHQLQuery(hql);
        return (long) query.getSingleResult();
    }

    public void mark(String[] ids) {
        List<SimpleExpression> expressionList = new ArrayList<>();
        expressionList.add(Restrictions.in("id", CollectionUtil.arrayToSet(ids), true));
        List<Msg> os = getDao().findAll(expressionList);
        if (CollectionUtil.isNotEmpty(os)) {
            for (Msg o : os) {
                o.setReadState(ReadState.YD);
            }
        }

        msgDao.save(os);
    }
}
